package com.funmi.lizip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.base.ResultCode;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.Camera;
import com.funmi.lizip.entity.dto.camera.CameraAddRequest;
import com.funmi.lizip.entity.dto.camera.CameraQueryRequest;
import com.funmi.lizip.entity.dto.camera.CameraUpdateRequest;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.entity.vo.CameraVo;
import com.funmi.lizip.service.CameraService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yeyg
 * @since 2022-11-02
 */
@Api(tags = "红外相机模块")
@RestController
@RequestMapping("/infraredCamera")
public class CameraController {

    @Autowired
    private CameraService cameraService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "根据 红外相机ID 获取信息 ")
    @ApiImplicitParam(name = "id",value = "红外相机ID",dataTypeClass = Integer.class)
    @GetMapping("/{id}")
    public R position(@PathVariable Integer id){
        Camera camera = cameraService.getById(id);
        if (!ObjectUtils.isEmpty(camera) && !ObjectUtils.isEmpty(camera.getLayPic())){
            JSONArray layPic = camera.getLayPic();
            Object[] objects = layPic.toArray();
            List<Object> collect = Arrays.stream(objects).collect(Collectors.toList());
            List<Object> list = collect.stream().map(fileName -> {
                return fileName = "Camera" + "\\" + fileName;
            }).collect(Collectors.toList());
            JSONArray array = JSONArray.parseArray(JSON.toJSONString(list));
            camera.setLayPic(array);
        }
        return R.success().data(camera);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "根据输入进行检索")
    @GetMapping("")
    public R queryList(CameraQueryRequest request){
        long current = 1;
        long size = 10;
        Camera cameraQuery = new Camera();
        if (request != null){
            BeanUtils.copyProperties(request, cameraQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        cameraQuery.setPointNo(null);
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>(cameraQuery);
        queryWrapper.orderByDesc("create_at");
        if(!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getPointNo())){
            queryWrapper.like("point_no",request.getPointNo());
        }

        Page<Camera> cameraPage = cameraService.page(new Page<>(current, size), queryWrapper);
        Page<CameraVo> cameraVoPage = new PageDTO(cameraPage.getCurrent(), cameraPage.getSize(), cameraPage.getTotal());
        List<CameraVo> cameraVoList = cameraPage.getRecords().stream().map(camera -> {
            CameraVo cameraVo = new CameraVo();
            BeanUtils.copyProperties(camera, cameraVo);
            return cameraVo;
        }).collect(Collectors.toList());
        cameraVoPage.setRecords(cameraVoList);
        return R.success().data(cameraVoPage);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改")
    @PutMapping("/{id}")
    public R updateInfraredCamera(@RequestBody HashMap<String, Object> requests){
        CameraUpdateRequest request = JSONObject.parseObject(JSONObject.toJSONString(requests), CameraUpdateRequest.class);

        if (request == null || request.getId() == null) {
            throw new ApplicationException(ResultCode.PARAMS_ERROR);
        }

        Camera camera = new Camera();
        BeanUtils.copyProperties(request, camera);
        boolean result = cameraService.updateById(camera);
        if (result) {
            return R.success().message("保存成功");
        } else {
            throw new ApplicationException("保存失败");
        }
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增")
    @PostMapping("")
    public R addInfraredCamera(@RequestBody(required = false) CameraAddRequest request) throws IOException {
        if (request == null) {
            throw new ApplicationException(ResultCode.PARAMS_ERROR);
        }
        Camera camera = new Camera();
        BeanUtils.copyProperties(request, camera);
        camera.setCreateAt(LocalDateTime.now());
        JSONArray objects = new JSONArray();
        for(String file : request.getLayPic()) {

            File dest = new File(PathEnum.PATH.getText() + "\\" + "Camera" + "\\" + camera.getPointNo() + "\\" + file);
            // 将暂存的图片移动到指定文件夹中
            // 文件夹名称
            Path directories = Files.createDirectories(dest.getParentFile().toPath());
            File startFile = new File(PathEnum.PATH.getText() + "\\" + file);
            boolean b = startFile.renameTo(dest);
            if (!b) {
                throw new ApplicationException("图片保存失败");
            }else {
                objects.add(camera.getPointNo() + "\\" + file);
            }
        }
        camera.setStatus(1);
        camera.setLayPic(objects);
        boolean result = cameraService.save(camera);
        if (result) {
            return R.success().message("新增成功");
        } else {
            throw new ApplicationException("新增失败");
        }
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public R<?> deleteInfraredCamera(@PathVariable Integer id){
        if (id <= 0) {
            throw new ApplicationException(ResultCode.FILE_DELETE_ERROR);
        }
        boolean result = cameraService.removeById(id);
        if (result) {
            return R.success().message("删除成功");
        } else {
            return R.fail().message("删除失败");
        }
    }

}

